package day11;

import java.security.PublicKey;
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//a.银行账户余额查询与转账,使用ReentrantReadWriteLock实现银行账户系统，
// 支持并发余额查询但互斥转账操作  (提示: 提供三个方法 查询(读锁)  存款(写锁)  取款(写锁))
public class Home3 {
    ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();
    static double balance=1000;
    int amount;
    public class BankAccount{
        double balance;
        public BankAccount(double balance) {
            this.balance = balance;
        }
    }
    public double check(){
        rwlock.readLock().lock();
        rwlock.readLock().unlock();
        return balance;
    }
    public void deposit(int amount) {//存 写
        String name=Thread.currentThread().getName();
        rwlock.writeLock().lock();
        if(amount<=0){
            System.out.println("请存入正数的金额");
        }else{
            balance+=amount;
            System.out.println("您已成功存入"+amount+",当前余额"+balance);
        }
        rwlock.writeLock().unlock();
    }
    public void withdraw(int amount){//取 写
        String name=Thread.currentThread().getName();
        rwlock.writeLock().lock();
        if(amount>=balance){
            System.out.println("您的余额不足！");
        }else{
            balance-=amount;
            System.out.println("您已成功取走"+amount+",还剩余额"+balance);
        }
        rwlock.writeLock().unlock();
    }

    public static void main(String[] args) {
        String name=Thread.currentThread().getName();
        Random r=new Random();
        Home3 h3=new Home3();
        new Thread(()->{
            while (true){
                int i=r.nextInt(2);
                if(i==0){
                    h3.deposit(r.nextInt(100));
                }else {
                    h3.withdraw(r.nextInt(200));
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
